from fastapi import APIRouter, HTTPException, Depends
from pydantic import BaseModel, Field
from typing import Dict, Any
from app.api.avatar_agent import AvatarAgent
from sqlalchemy.orm import Session
from ..database import get_db
from .. import models
from ..deps import get_current_user
from app.crud import chat as chat_crud

router = APIRouter()

class UserInput(BaseModel):
    message: str

class AvatarProfileInput(BaseModel):
    """化身配置输入模型"""
    username: str = Field(..., description="用户名")
    personality: str = Field(..., description="性格特征描述")
    interests: str = Field(..., description="兴趣爱好")
    values: str = Field(..., description="价值观")
    speaking_style: str = Field(..., description="说话风格")
    sample_dialogue: str = Field(..., description="示例对话")

    class Config:
        json_schema_extra = {
            "example": {
                "username": "张三",
                "personality": "开朗、乐观、善于交际",
                "interests": "旅游、摄影、美食",
                "values": "诚实守信、追求进步、关心他人",
                "speaking_style": "语气温和、用词亲切、喜欢用生动的比喻",
                "sample_dialogue": "用户：你怎样看待旅行？\n你：旅行是一种探索未知、体验不同文化和生活方式的方式。它不仅能让人放松身心，还能拓宽视野，增长见识。"
            }
        }

class ResponseModel(BaseModel):
    data: Any
    code: str
    message: str

@router.post("/avatar/chat/{avatar_id}", response_model=ResponseModel)
async def avatar_chat(
    avatar_id: str, 
    user_input: UserInput,
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """与指定化身对话"""
    try:
        avatar_agent = AvatarAgent.from_db(db, avatar_id, current_user.id)
        response = avatar_agent.chat(user_input.message)
        return {
            "data": response,
            "code": "200",
            "message": "Chat response generated successfully"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/avatar/new-session/{avatar_id}", response_model=ResponseModel)
async def create_new_chat_session(
    avatar_id: str,
    current_user: models.User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建新的聊天会话"""
    try:
        session = chat_crud.create_avatar_chat_session(db, current_user.id, avatar_id)
        return {
            "data": {
                "session_id": session.id,
                "created_at": session.created_at
            },
            "code": "200",
            "message": "New chat session created successfully"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
